package com.security.gateway.filter;

import com.google.common.collect.Maps;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Author yanggld
 * @Date 2020/3/11-10:48
 */
@Slf4j
@Component
public class AuthorizationFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 3;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        log.info("******************Authorization start****************");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        if (isNeedAuth(request)) {
            TokenInfo tokenInfo = (TokenInfo)request.getAttribute("tokenInfo");

            if (tokenInfo != null && tokenInfo.isActive()) {
                if (!hasPerssion(tokenInfo, request)) {
                    log.error("audit log update fail 403");
                    handleError(403, request);
                }
                ctx.addZuulRequestHeader("username", tokenInfo.getUser_name());
            } else {
                if (!StringUtils.startsWith(request.getRequestURI(), "/auth")) {
                    log.error("audit log update fail 401");
                    handleError(401, request);
                }
            }
        }


        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, List<String>> params = ctx.getRequestQueryParams();
        if (params == null) {
            params = Maps.newHashMap();
        }
        List<String> userId = Arrays.asList("heheh1");
        params.put("usernameZZZ", userId);
        ctx.setRequestQueryParams(params);
        return null;
    }

    private void handleError(int status, HttpServletRequest request) throws ZuulException {
        throw new ZuulException(new RuntimeException(), status, "权鉴失败");
    }

    private boolean hasPerssion(TokenInfo tokenInfo, HttpServletRequest request) {
        return RandomUtils.nextInt() % 20000000 != 0;
    }

    private boolean isNeedAuth(HttpServletRequest request) {
        return true;
    }
}
